using System.Web;
using System.Web.UI.WebControls;
using log4net;
using System.IO;

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

public class SyncHelper
{
    private static readonly ILog nlog = LogManager.GetLogger("WebSynchronizer");
    public static void Synchronize(string srcEntries, string dstFolder, Repeater dstRepeater, Synchronize.FileSystem srcSystem, Synchronize.FileSystem dstSystem)
    {
        if (!string.IsNullOrEmpty(HttpContext.Current.Request[srcEntries]))
        {
            foreach (string srcEntry in HttpContext.Current.Request[srcEntries].Split(','))
            {
                Synchronize.FileSystemEntry _entry = new Synchronize.FileSystemEntry();
                string[] srcParts = srcEntry.Split(':');
                _entry.IsDirectory = bool.Parse(srcParts[0]);
                _entry.Path = srcParts[1];
                SynchronizeEntry(_entry, dstFolder, srcSystem, dstSystem);
            }
            dstRepeater.DataBind();
        }
    }

    private static void SynchronizeEntry(Synchronize.FileSystemEntry _entry, string dstFolder, Synchronize.FileSystem srcSystem, Synchronize.FileSystem dstSystem)
    {
        nlog.InfoFormat("Sync [{0}] -> [{1}] isDirectory {2}", _entry.Path, dstFolder, _entry.IsDirectory);

        if (_entry.IsDirectory)
        {
            string subFolder = Path.Combine(dstFolder, new DirectoryInfo(_entry.Path).Name);
            foreach (Synchronize.FileSystemEntry entry in srcSystem.GetFileSystemEntries(_entry.Path))
            {
                if (!entry.IsSymbolic)
                {
                    SynchronizeEntry(entry, subFolder, srcSystem, dstSystem);
                }
            }
        }
        else
        {
            byte[] bytes = srcSystem.ReadFile(_entry.Path);
            dstSystem.WriteFile(dstFolder, _entry.Path, bytes);
        }
    }
}
